package com.foodcommunity.controller;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.LoginDTO;
import com.foodcommunity.dto.RegisterDTO;
import com.foodcommunity.dto.UpdateProfileDTO;
import com.foodcommunity.entity.User;
import com.foodcommunity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;

    @Value("${upload.path}")
    private String uploadPath;
    
    @PostMapping("/login")
    @ResponseBody
    public Result<User> login(@Valid @RequestBody LoginDTO loginDTO, HttpSession session) {
        Result<User> result = userService.login(loginDTO);
        if (result.getCode() == 200) {
            session.setAttribute("user", result.getData());
        }
        return result;
    }
    
    @PostMapping("/logout")
    @ResponseBody
    public Result<Void> logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success(null);
    }
    
    @GetMapping("/current")
    public Result<User> getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }
        return Result.success(user);
    }
    
    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody RegisterDTO registerDTO) {
        return userService.register(registerDTO);
    }
    
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        boolean exists = userService.checkUsername(username);
        return Result.success(exists);
    }

    @PostMapping("/update-profile")
    @ResponseBody
    public Result<User> updateProfile(@RequestBody UpdateProfileDTO profileDTO, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return Result.error("未登录");
        }

        // 更新用户信息
        currentUser.setNickname(profileDTO.getNickname());
        currentUser.setBio(profileDTO.getBio());
        currentUser.setFoodPreference(profileDTO.getFoodPreference());
        currentUser.setCookingSkill(profileDTO.getCookingSkill());
        currentUser.setUpdateTime(LocalDateTime.now());

        if (userService.updateUser(currentUser)) {
            session.setAttribute("user", currentUser);
            return Result.success(currentUser);
        }
        return Result.error("更新失败");
    }

    @GetMapping("/edit-profile")
    public String profile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "user/profile";
    }

    @PostMapping("/upload/avatar")
    @ResponseBody
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        String fileName = handleFileUpload(file, "avatar");
        if (fileName == null) {
            return Result.error("上传失败");
        }

        // 更新用户头像
        user.setAvatar(fileName);
        if (userService.updateUser(user)) {
            session.setAttribute("user", user);
            return Result.success(fileName);
        }
        return Result.error("更新失败");
    }

    @PostMapping("/upload/cover")
    @ResponseBody
    public Result<String> uploadCover(@RequestParam("file") MultipartFile file, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }

        String fileName = handleFileUpload(file, "cover");
        if (fileName == null) {
            return Result.error("上传失败");
        }

        // 更新用户背景
        user.setBackgroundImage(fileName);
        if (userService.updateUser(user)) {
            session.setAttribute("user", user);
            return Result.success(fileName);
        }
        return Result.error("更新失败");
    }
    
    @GetMapping("/{id}")
    public Result<User> getUserInfo(@PathVariable Long id) {
        return userService.getUserInfo(id);
    }

    private String handleFileUpload(MultipartFile file, String type) {
        if (file.isEmpty()) {
            return null;
        }

        try {
            // 创建年月日目录
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            String directory = uploadPath + "/" + type + "/" + datePath;
            File dir = new File(directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成新的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            File destFile = new File(dir, newFileName);
            file.transferTo(destFile);

            // 返回可访问的URL路径
            return "/uploads/" + type + "/" + datePath + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
} 